package com.example.lkfy.controller;

import com.example.lkfy.model.R;
import com.example.lkfy.utils.RedisMqUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("topic")
public class TopicController {

    @Autowired
    private RedisMqUtil redisMqUtil;

    /**
     * 推送 标签的消息
     * @param data
     * @return
     */
    @GetMapping("/tag")
    public R tag(String data){
        redisMqUtil.toMq("tag", data);
        return R.ok();
    }

    private void jedis(){
        Jedis jedis = new Jedis("192.168.254.128",6379);
        jedis.auth("root123");
        try {

            String key_s = "user_name";// 抢到的用户
            String key = "test_count";// 商品数量
            String clientName = UUID.randomUUID().toString().replace("-", "");// 用户名字

            while (true) {
                try {
                    jedis.watch(key);// key加上乐观锁
                    System.out.println("用户:" + clientName + "开始抢商品");
                    System.out.println("当前商品的个数：" + jedis.get(key));
                    int prdNum = Integer.parseInt(jedis.get(key));// 当前商品个数
                    if (prdNum > 0) {

                        Transaction transaction = jedis.multi();// 标记一个事务块的开始
                        transaction.set(key, String.valueOf(prdNum - 1));
                        List<Object> result = transaction.exec();// 原子性提交事物
                        if (result == null || result.isEmpty()) {
                            System.out.println("用户:" + clientName + "没有抢到商品");// 可能是watch-key被外部修改，或者是数据操作被驳回
                        } else {
                            jedis.sadd(key_s, clientName);// 将抢到的用户存起来
                            System.out.println("用户:" + clientName + "抢到商品");
                            break;
                        }
                    } else {
                        System.out.println("库存为0，用户:" + clientName + "没有抢到商品");
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                    jedis.unwatch();// exec，discard，unwatch命令都会清除连接中的所有监视

                }
            } // while
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("redis bug:" + e.getMessage());
        } finally {
            // 释放jedis连接
            try {
                jedis.close();
            } catch (Exception e) {
                System.out.println("redis bug:" + e.getMessage());
                // TODO Auto-generated catch block

            }
        }
    }

}
